<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTag } from 'element-plus'
import { Form } from '@/components/Form'
import {
  ElOption,
  ElOptionGroup,

} from 'element-plus'
import { Table } from '@/components/Table'
import { addCompany, getClassListApi, getUserList, getCompanyList, editCompany, uploadFile } from '@/api/table'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive, onMounted } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

import { useUserStoreWithOut } from '@/store/modules/user'
import { formatToDate, unique, getHourMins } from "@/utils/dateUtil"
const userStore = useUserStoreWithOut()


const ids = ref<string[]>([])
const classOption = reactive([])
const schema = reactive([])
const schemaFlag = ref(false)
const cid = ref(0)
onMounted(async () => {
  let { data } = await getClassListApi({ pageIndex: 1, pageSize: 999 })
  // {label:"",value:""}
  for (var i = 0; i < data.list.length; i++) {
    classOption.push({ label: data.list[i].bak + data.list[i].name, value: data.list[i].cid })
  }
  // console.log(userStore.userInfo.roles,31)
  // if(userStore.roles)
  // 判断用户是否为 老师 如果是 可以给所有学生添加面试
  if (userStore.userInfo.roles === 'teacher') {
    // 获取用户列表
    let res = await getUserList({ pageIndex: 1, pageSize: 999 }).catch(() => { })
    let list = res.data.list
    let userOptions = []
    for (var i = 0; i < list.length; i++) {
      if (list[i].username.indexOf("teacher") === -1) {
        userOptions.push({
          value: list[i].id,
          label: list[i].nickname
        })
      }
    }
    allSchemas.formSchema.push({
      field: 'mid',
      label: "选择面试人",
      component: 'Select',
      componentProps: {
        options: userOptions,
        on: {
          change: (item) => {
          }
        },
      }
    })
    cid.value = classOption[0].value
    console.log(cid.value)
    getList()
    schema.push({
      field: 'cid',
      label: "班级",
      component: 'Select',
      componentProps: {
        options: classOption,
        on: {
          change: (item) => {
            cid.value = item
            // console.log(tableMethods,120000)
            tableMethods.refresh()
          }
        },
        slots: {
          default: (options: SelectOption[]) => {
            // console.log(options,115)
            if (options.length) {
              return options?.map((v) => {
                // console.log(v,118)
                return <ElOption key={v.value} label={v.label} value={v.value} />
              })
            } else {
              // console.log("zoule")
              return null
            }
          },
          prefix: () => <Icon icon="ep:calendar" />
        }
      }
    })

    // console.log(schema,92)
    schemaFlag.value = true
  }

})

let columns = reactive([
  {
    field: 'nickname',
    label: "名字",
    fixed: true,
    showOverflowTooltip: false,
    form: {
      hidden: true
    },
    colProps: {
      width: 100
    }
  }
])
let companyData = []
const companyNameClick = (val) => {
  console.log(val)
  dialogTitle.value = "修改"
  // for(let i=0;i<companyData.length;i++){
  //   if(companyData[i].id===val.id){
  //     currentRow.value = companyData[i]
  //     break
  //   }
  // } 
  const item = companyData.find(item => item.id === val.id);
  if (item) {
    currentRow.value = item;
  }
  dialogVisible.value = true
  actionType.value = ''
}
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getCompanyList({
      cid: cid.value
    })
    companyData = res.data
    // console.log(res,67)
    // 首先确定 有多少列 姓名
    let columnsBak = []
    for (let i = 0; i < res.data.length; i++) {
      columnsBak.push({
        field: formatToDate(res.data[i].times * 1, "YYYYMMDD"),
        label: formatToDate(res.data[i].times * 1),
        showOverflowTooltip: false,
        form: {
          hidden: true
        },
        slots: {
          default: (data) => {
            // console.log(data.row[data.column.property],90)
            let arr = []
            if (data.row[data.column.property]) {
              arr = data.row[data.column.property]
            }

            return arr.map(val => {
              // console.log(val.value, 101)
              return <div onClick={() => { companyNameClick(val) }}>{val?.value}</div>
            })
          }
        }
      })
    }

    columns = [
      {
        field: 'nickname',
        label: "名字",
        fixed: true,
        showOverflowTooltip: false,
        form: {
          hidden: true
        },
        colProps: {
          width: 100
        }
      }
    ]
    // console.log(JSON.stringify(unique(columns, 'field')), 68)
    columnsBak = unique(columnsBak, 'field').sort((a, b) => { if (a.field === "nickname") { return 1 } return a.field.localeCompare(b.field) })
    for (let i = 0; i < columnsBak.length; i++) {
      columns.push(columnsBak[i])
    }

    let newValueArr = []

    for (let i = 0; i < res.data.length; i++) {
      let key = formatToDate(res.data[i].times * 1, "YYYYMMDD")
      let flag = false
      for (let j = 0; j < newValueArr.length; j++) {
        if (newValueArr[j].nickname === res.data[i].nickname) {
          // 数据合并
          // 判断 属性是否存在 如果不存在 就赋值个空数组
          if (!newValueArr[j][key]) {
            newValueArr[j][key] = []
          }
          // console.log(newValueArr[j][key],130)
          // 进行数据合并
          newValueArr[j][key].push({ id: res.data[i].id, value: res.data[i].company + `(${getHourMins(res.data[i].times * 1, ":")})` })
          // console.log(newValueArr,129)
          flag = true
        }
      }
      if (!flag) {
        // 数据添加
        let objArr = { nickname: "" }
        objArr.nickname = res.data[i].nickname
        objArr[key] = []
        objArr[key].push({ id: res.data[i].id, value: res.data[i].company + `(${getHourMins(res.data[i].times * 1, ":")})` })
        newValueArr.push(objArr)
      }
    }

    // console.log(newValueArr, 85)
    return {
      list: newValueArr,
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const { t } = useI18n()



// @ts-ignore
const { allSchemas } = useCrudSchemas([])





allSchemas.formSchema.push({
  field: 'company',
  label: '面试公司信息',
  component: 'Input',
  colProps: {
    span: 24
  }
})
allSchemas.formSchema.push({
  field: 'times',
  component: 'DatePicker',
  label: "面试时间",
  componentProps: {
    type: 'datetime',
    shortcuts: [
      {
        text: t('formDemo.today'),
        value: new Date()
      },
      {
        text: t('formDemo.yesterday'),
        value: () => {
          const date = new Date()
          date.setTime(date.getTime() - 3600 * 1000 * 24)
          return date
        }
      },
      {
        text: t('formDemo.aWeekAgo'),
        value: () => {
          const date = new Date()
          date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
          return date
        }
      }
    ]
  }
})
allSchemas.formSchema.push({
  field: 'remark',
  label: '备注',
  component: 'Input',
  colProps: {
    span: 24
  }
})
allSchemas.formSchema.push({
  field: 'callbackmsg',
  component: 'Editor',
  value: '还没开始',
  label: "面试反馈",
  componentProps: {
    editorConfig: {
      MENU_CONF: {
        uploadImage: {
          server: '/zzmapi/user/upload',
          headers: {
            Token: userStore.userInfo.token ?? ''
          },
          meta: {
            editor: true
          },
          name: 'file',
          fieldName: "file",
        },
        uploadVideo: {
          server: '/zzmapi/user/upload',
          headers: {
            Token: userStore.userInfo.token ?? ''
          },
          meta: {
            editor: true
          },
          name: 'file',
          fieldName: "file",
        }
      }
    }
  },
  colProps: {
    span: 24
  }
})


const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = ''
}





const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  // console.log(formData, 210)

  if (formData) {
    saveLoading.value = true
    let res
    if (!formData.id) {
      if (!formData.mid) {
        formData.mid = userStore.userInfo.id
      }
      formData.times = new Date(formData.times).getTime()
      // console.log(userStore.userInfo)
      res = await addCompany(formData)
        .catch(() => { })
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      console.log(formData)
      res = await editCompany(formData)
        .catch(() => { })
        .finally(() => {
          saveLoading.value = false
        })
    }



    if (res) {
      dialogVisible.value = false
      getList()
    }
  }
}
const fileRef = ref()
const FileAction = () => {
  // console.log(fileRef.value)
  // 让input file 触发点击事件
  fileRef.value.click()
}
const fileChange = () => {
  uploadFile(fileRef.value.files[0]).then(e => {
    console.log(e, 361)
  }).catch(e => {
    console.log(e, 363)
  })
  // axios.post('/zzmapi/user/upload', formData, {

}
</script>

<template>
  <ContentWrap>
    <Form :schema="schema" v-if="schemaFlag" label-width="auto" />
  </ContentWrap>
  <ContentWrap>
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton type="primary" @click="FileAction">文件上传</BaseButton>
      <input type="file" ref="fileRef" @change="fileChange" style="display: none" />

    </div>
    <Table :columns="columns" stripe :data="dataList" :loading="loading" />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :form-schema="allSchemas.formSchema"
      :current-row="currentRow" />

    <Detail v-if="actionType === 'detail'" :detail-schema="allSchemas.detailSchema" :current-row="currentRow" />

    <template #footer>
      <BaseButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>


</template>
